package fileIO;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

/**
 * @Author liangzai
 * @Description:
 */
public class Demo1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的目录:");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()){
            System.out.println("输入的不是目录!");
            return;
        }
        System.out.println("请输入关键字:");
        String keyWord = scanner.next();
        scanDir(rootFile,keyWord);
    }

    private static void scanDir(File rootFile, String keyWord) {
        File[] files = rootFile.listFiles();
        if (files == null) {
            return;
        }
        for(File file : files){
            if(file.isFile()){
                dealFile(file, keyWord);
            }else {
                scanDir(file, keyWord);
            }
        }
    }

    private static void dealFile(File file, String keyWord) {
        if(file.getName().contains(keyWord)){
            System.out.println("文件名包括关键字:"+file.getAbsolutePath());
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)){
            while(true) {
                char[] chars = new char[1024];
                int n = reader.read(chars);
                if (n == -1) {
                    break;
                }
                stringBuilder.append(chars,0,n);
            }
        }catch (IOException e){
            throw new RuntimeException();
        }
        if(stringBuilder.indexOf(keyWord)>=0){
            System.out.println("文件内容包括关键字:"+file.getAbsolutePath());
        }
        return;
    }
}
